<?php 
class Mod_Lib extends Model
{
	public $_table 	= '';
	public $_limit 	= '';
	public $_offset = '';
	public $_field_where = array();
	public $_value = array();
	
	function Mod_Lib()
	{
		parent::Model();
	}	
	
	/**
	* @desc: get total record of a table whith name: $_table.
	* @param: 
	* +> $_table: table name.
	* +> $_field_where : list of field will using to compare. 
	* +> $_value: list value corressponding with $_field.
	* @return: total record of table name $_table.	
	* 	Example : $_table='table'; $_field_where = array('id'=>'1','status'=>'1'); 
	* @date modified : 20110319
	*/
	function count_all_record($_table,$_field_where=null)
	{
		if(isset($_field_where) && !empty($_field_where)){			
			foreach($_field_where as $_key=>$_value){
					$this->db->where($_key,$_value);					
			}			
		}
		return $this->db->count_all_results($_table);
	}
	
	/**
	 * @desc : function get all information for each record of a table with query limited. and get data join with a another table.
	 * @param   : 
	 * @return : a array list all record.
	 * @date modified: 20110319
	 * */
	
	function get_record_table(
	$_table=null,
	$_limit=null,
	$_offset=null,
	$_field_order=null,
	$_order_by = 'DESC',
	$_field_where=null,
	$_join_table=null
	,$_field_join=null,
	$_type_join=null)
	{
		if(isset($_field_where) && !empty($_field_where)){			
			foreach ($_field_where as $_key=>$_value){
				$this->db->where($_key,$_value);					
			}
		}
		if(isset($_join_table) && !empty($_join_table)){			
			$this->db->join($_join_table,$_field_join,$_type_join);
		}
		$this->db->limit($_limit,$_offset);		
		$this->db->order_by($_field_order,$_order_by);
		
		return $this->db->get($_table)->result_array();		
	}
	/**
	* @desc: run a query normal $query.
	* @return: return a array.
	* @author: hiennv
	*/
	function run_query($query)
	{
		$result = $this->db->query($query);
		return $result->result_array();
	}
	/**
	 * */
	function get_record_table_nojoin(
	$_table=null,
	$_limit=null,
	$_offset=null,
	$_field_order=null,
	$_order_by = 'DESC',
	$_field_where=null)
	{
		if(isset($_field_where) && !empty($_field_where)){			
			foreach ($_field_where as $_key=>$_value){
				$this->db->where($_key,$_value);					
			}
		}
		$this->db->limit($_limit,$_offset);		
		$this->db->order_by($_field_order,$_order_by);
		
		return $this->db->get($_table)->result_array();		
	}
	
	
	/**
	 * @desc : process to update status of record in a table.
	 * @param :
	 * +> $_table: name of table.
	 * +> $_status: status need update of record.
	 * +> $_id_record: id of record. 
	 * +> $_fieldname: name of field.
	 * +> $_field_where: field to compare with where.
	 * @date modified: 20110319.
	 * */
	function active_record($_table=null,$_status=null,$_fieldname=null,
	$_field_where = null,$_id_record = null)
	{
		if($_status == 1){
			$data = array($_fieldname=>'0');
		}else {
			$data = array($_fieldname=>'1');
		}
		$this->db->where($_field_where,$_id_record);
		$this->db->update($_table,$data);
	}
	
	
	/**
	 * @desc: get all record of a table with status of a field is $_value.
	 * */
	function get_all_record_table($_table,$_field_where = array())
	{
		if(!empty($_field_where) && isset($_field_where)){
			foreach ($_field_where as $_key=>$_value){
				$this->db->where($_key,$_value);
			}
		}
		
		return $this->db->get($_table)->result_array();
	}
	
	/**
	 * @desc: get 
	 * */
	
	
	public function admin_edit($table,$field)
	{
		foreach($field as $key=>$value){
			$this->db->where($key,$value);
		}
		return $this->db->get($table)->result_array();
	}
	/*Function process update status of record*/
	function admin_active($table,$field_name,$value,$data = array())
	{
		$this->db->where($field_name,$value);		
		$this->db->update($table,$data);
	}	
	
	/**
	 * @desc: get detail a record of a table. Can using for case $_table join with another table.
	 * @param : 
	 * @return : return a array containt all information of a record in a table.
	 * @date modified: 20110319
	 * */
	function get_detail_record_join($_table=null,$_id_record=null,$_fieldname = 'id',$_table_join=null,$_join_where=null,$_type_join=null)
	{
		
		if(isset($_table_join) && !empty($_table_join) && isset($_join_where) && !empty($_join_where)){
			if($_table_join == 'khoahoc' && $_table=='lophoc'){
				
				$this->db->select("$_table.*");
				$this->db->select("$_table_join.id_khoahoc as idkh,$_table_join.tenkhoahoc,$_table_join.tenkhoahoc");
			}
			$this->db->join($_table_join,$_join_where,$_type_join);
		}
		$this->db->where($_fieldname,$_id_record);		
		return $this->db->get($_table)->result_array();
		
	}
	
	/*Function list all record of table name "$table" */
	function admin_load_list($table,$field,$order_by, $where = array(),$limit = null,$offset = null)	
	{
		if ($limit!=null || $offset !=null){
			$this->db->limit($limit,$offset);
		}
		if (isset($where) || !empty($where)){
			foreach($where as $key=>$value){
				$this->db->where($key,$value);
			}
		}
		if (isset($order_by)&!empty($order_by)&isset($field)&!empty($field)){
			$this->db->order_by($field,$order_by);
		}		
		return $this->db->get($table)->result_array();
	}
	
	
	/*Load detail a record of table name: $table, id of record: $id*/
	function get_detail_record($table, $field,$id)
	{		
		$this->db->where($field,$id);
		$result = $this->db->get($table)->result_array();
		if(!empty($result))	{
			return $result[0];
		}else {
			return '';
		}
	}

	
	/**
	* get permision of a user from $table
	*/
	function get_per_user($table,$user_id,$filed_where = array())
	{
		if(isset($filed_where) && !empty($filed_where)){
			foreach($filed_where as $key=>$value){
				$this->db->where($key,$value);
			}			
		}
		$result = $this->db->get($table)->result_array();
		if(!empty($result)){
			return $result[0];
		}else {
			return '';
		}
	}
	// loadd_all admin coder ducquang
	function count_all($table,$select,$where,$like,$join)
	{
		if (isset($select) && !empty($select))
		{
			$this->db->select($select);
		}
		if (isset($where) && !empty($where))
		{
			foreach ($where as $key=>$value)
			{
				$this->db->where($key,$value);
			}
		}
		if (isset($like) && !empty($like))
		{
			foreach ($like as $key=>$value)
			{
				$this->db->like($key,$value);
			}
		}
		if (isset($join) && !empty($join))
		{
			foreach ($join as $key=>$value)
			{
				$this->db->join($key,$value);
			}
		}
		return $this->db->count_all_results($table);
	}
	function load_all($table,$select,$where,$like,$join,$limit,$offset,$order)
	{
		if (isset($select) && !empty($select))
		{
			$this->db->select($select);
		}
		if (isset($where) && !empty($where))
		{
			foreach ($where as $key=>$value)
			{
				$this->db->where($key,$value);
			}
		}
		if (isset($like) && !empty($like))
		{
			foreach ($like as $key=>$value)
			{
				$this->db->like($key,$value);
			}
		}
		if (isset($join) && !empty($join))
		{
			foreach ($join as $key=>$value)
			{
				$this->db->join($key,$value);
			}
		}
		if (isset($limit) && !empty($limit))
		{
			if (isset($offset) && !empty($offset))
			{
				$this->db->limit($limit,$offset);
			}else{
				$this->db->limit($limit);
			}
		}
		if (isset($order) && !empty($order))
		{
			foreach ($order as $key=>$value)
			{
				$this->db->order_by($key,$value);
			}
		}
		return $this->db->get($table)->result_array();
	}
	///////////////////////////////////////////////////////////////////////////////////
	function load_all_admin($table,$select,$where=array(),$limit,$offset,$order=array())
	{
		if (!empty($select) && isset($select))
		{
			$this->db->select($select);
		}
		if (!empty($where) && isset($where))
		{
			foreach ($where as $key=>$value)
			{
				$this->db->where($key,$value);
			}
		}
		if (!empty($limit) && isset($limit))
		{
			if (!empty($offset) && isset($offset))
			{
				$this->db->limit($limit,$offset);
			}else{
				$this->db->limit($limit);
			}
		}
		if (!empty($order) && isset($order))
		{
			foreach ($order as $key=>$value)
			{
				$this->db->order_by($key,$value);
			}
		}
		return $this->db->get($table)->result_array();
	}

	function admin_new($table,$filed_sort,$type_sort)
	{
		$this->db->order_by($filed_sort,$type_sort);
		$this->db->limit(1);
		return $this->db->get($table)->result_array();
	}
	
	// move to general, in here we only use function general, not define clear a parameter
	function permis_menu_admin($id)
	{
		$sql = " SELECT DISTINCT pa.id as permis_admin_id,pa.access,pa.additional,pa.edit,pa.del,ma.id as menu_admin_id, ma.name FROM atb_permis_admin pa, atb_menu_admin ma WHERE pa.admin_id = '$id' AND ma.id = pa.menu_admin_id ORDER BY ma.id ASC";
		return $this->db->query($sql)->result_array();
	}
	
	// get max of field in a table
	function select_max($field, $table)
	{
		$this->db->select_max($field);
		$result = $this->db->get($table)->result_array();
		return $result[0];
	}
	// we will use function of codeigniter $this->db->insert_id(), so we don't need this function 
	function getLastInserted() {
		 return $this->db->insert_id();
	}
	/**
	* @desc: get detail a record of a table with condition is define in $where , $where will is a array.
	* @return: return a array show all information of a record in a table $table.
	* @date modified: 20110319.
	*/
	function get_detail($table,$where = array())
	{
		foreach($where as $key=>$value){
			$this->db->where($key,$value);
		}
		$result  = $this->db->get($table)->result_array();
		if(!empty($result)){
			return $result[0];
		}else {
			return '';
		}
	}	
	
	/**
	* @desc: get all related of  a record of a table with condition is define in $condition , $condition will is a array.
	* @return: return a array show all record related.
	* @date modified: 20110319.
	*/
	function get_relate($table,$field,$value_field,$condition = array())
	{
		if (!empty($condition)){
			foreach($condition as $key=>$value){
				$this->db->where($key,$value);
			}
		}
		$this->db->where($field.' !='.$value_field);
		$result = $this->db->get($table)->result_array();
		if(!empty($result)){
			return $result;
		}else {
			return '';
		}
		
	}
	
	/**
	* @desc: get random a record of a table with condition is define in $where , $where will is a array.
	* @return: return a array.
	* @date modified: 20110319.
	*/
	function get_random_record($table,$where = '')
	{
		if(is_array($where)){
			foreach($where as $key=>$value){
				$this->db->where($key,$value);
			}
		}else{
			$this->db->where($where);
		}
		$result  = $this->db->get($table);
		if(!empty($result)){
			return $result[0];
		}else {
			return '';
		}
	}		

	

	function get_config_site($table)
	{
		$result = $this->db->get($table)->result_array();
		if(!empty($result)){
			return $result[0];
		}else {
			return '';
		}
	}

	
	// 
	/*function get_email($table,$wheres)
	{
		if(!empty($wheres)){
			foreach($wheres as $key=>$value){
				$this->db->where($key,$value);
			}
		}	
		$result = $this->db->get($table)->result_array();
		$em_arr = '';
		if(!empty($result)){
			$i=0;
			foreach($result as $em){
				if($i==0){
					$em_arr.=$em['email'] ;
				}else{
					$em_arr.=','.$em['email']; 
				}				
				$i++;
			}
		}
		
		return $em_arr;	
	}*/	
	/**
	* @desc: Check permision for any thing in admin
	* @param: $table: name of table, @wheres: is a array initial = NULL, list all where of query
	*/
	function load_permis($table, $wheres) 
	{
		if(!empty($wheres)){
			foreach($wheres as $key=>$value){	
				$this->db->where($key,$value);
			}
		}
		$num = $this->db->get($table)->num_rows();
		if($num > 0){
			return true;
		}else {
			return false;
		}
	}

	function isEmpty($values)
	{
		if(!is_array($values)){
			if(empty($values)){
				return false;
			}else{
				return true;
			}		
		}else {
			foreach($values as $value){
				if(empty($value)){
				return false;
			}else{
				return true;
			}	
			}
		}		
	}
	/**
	* @desc: load  config when pagination.
	* @return: .
	* @date modified: 20110319.
	*/
	function load_config_paging($total,$url,$segmnet,$per_page)
	{
		$this->load->library('pagination');
		$config['total_rows'] =  $total;
		$config['base_url'] = site_url($url);
		$config['uri_segment'] = $segmnet;		
		$config['per_page'] = $per_page;
		$config['num_links'] = 8;
		//$config['num_links'] = 8;
		$this->pagination->initialize($config); 
	}
	
	function paging_ajax($limit,$start,$table)
	{
		
	}
	// active or unactive a field with value is define in a array single. 
	// example : $value_field_active = array('active'=> 1)
	function active_unactive($table,$value_field_active,$wheres)
	{
		if(isset($wheres)){
			foreach($wheres as $key=>$value){
				$this->db->where($key,$value);
			}
		}
		foreach($value_field_active as $key_ac=>$value_ac){
			$data = array($key_ac=>$value_ac);
			$this->db->update($table,$data);
		}
	}
	//create folder by year, then create folder by qui.in a folder of qui, we will create folder by name of user.
	function create_folder($f_current,$user_name)
	{
		$year = date('Y');
		// check folder exists?
		// if exists => check folder year exist?
		if(!file_exists($f_current.'/'.$year)){
			// case year don't exist.
			mkdir($f_current.'/'.$year);
			$y_folder = $f_current.'/'.$year;
		}else {
			$y_folder = $f_current.'/'.$year;
		}
		$qui = (int)date('m');
		if( ($qui>=1) && ($qui <= 3)){
			$f_qui = 'quarter1';
		}elseif($qui>3 && $qui<=6){
			$f_qui = 'quarter2';
		}elseif($qui>6 && $qui<=9){
			$f_qui = 'quarter3';
		}else{
			$f_qui = 'quarter4';
		}

		// check if exists $qui.
		if(!file_exists($y_folder.'/'.$f_qui)){
			mkdir($y_folder.'/'.$f_qui);	
			$q_folder = $y_folder.'/'.$f_qui;
		}else{
			$q_folder = $y_folder.'/'.$f_qui;
		}
		if(!file_exists($q_folder.'/'.$user_name)){
			mkdir($q_folder.'/'.$user_name);
			$u_folder = $q_folder.'/'.$user_name;
		}else {
			$u_folder = $q_folder.'/'.$user_name;
		}
//		if(!file_exists($u_folder.'/products')){
//			mkdir($u_folder.'/products');
//		}
//		if(!file_exists($u_folder.'/logos')){
//			mkdir($u_folder.'/logos');
//		}
//		if(!file_exists($u_folder.'/news')){
//			mkdir($u_folder.'/news');
//		}
		return $u_folder.'/';	
	}
	
	// process save data for a table with table $table, $id default  = 0.
	// +> if $id = 0 we will process insert array $data to table name $table.
	// +> if $id!=0  we will process update array $data to table name $table.
	// +> $where will is a array example: $where = array('id'=> 10),...
	function save($table, $data,$id = 0,$where='')
	{
		if($id==0){
			// insert data for table $table`
			$this->db->insert($table,$data);
		}else{	
			// update data for table $table 	
			$this->db->update($table,$data,$where);
		}
	}
	
	//function check permision of user: user can add or edit or delete or add ?
	function check_aed_action($table, $where)
	{
		foreach($where as $key=>$value){
			$this->db->where($key,$value);
		}
		if($this->db->get($table)->num_rows() > 0){
			return true;
		}else {
			return false;
		}		
	}
	
	function check_record_exists($table,$where)
	{
		foreach($where as $key=>$value){
			$this->db->where($key,$value);
		}
		if($this->db->get($table)->num_rows() > 0){
			return true;
		}else {
			return false;
		}
	}
	
	function calc_pagin_ajax($total,$per_page)
	{
		$pages = ceil($total/$per_page);
		echo '<ul id="pagination">';
		//Pagination Numbers
		for($i=1; $i<=$pages; $i++)
		{
			echo '<li id="'.$i.'">'.$i.'</li>';
		}
		echo '</ul> ';
	}
	
	/**
	* @desc: read all file have extension is .css in a folder to inlcude to the system.
	* @return : return is a array containt all files css of a folder.
	* @author : hiennv
	*/
	function read_css($dir)
	{
		$fp = opendir($dir);
		while ($file = readdir($fp)) {
				if (strpos($file, '.css',1))
					$results[] = $file;
			}
		closedir($fp);

	}
	
	function get_user_id($u_domain)
	{
		$this->db->where('mem_domain',$u_domain);
		$this->db->where('mem_status',1);
		$result = $this->db->get('member')->row();
		if($result != NULL){
			return $result->mem_id;
		}else {
			return ;
		}
	}
	/*
	* @author: hiennv
	* @desc: function create thumbnail for image, advanced : create thumbnail from file png haven't backgroud black.
	* To using it only need call: createthumb("img.gif", "tn_img.gif", 64,64,true, true, false);
	*/
	function createthumb($name, $newname, $new_w, $new_h, $border=false, $transparency=true, $base64=false) {
		if(file_exists($newname))
			@unlink($newname);
		if(!file_exists($name))
			return false;
		$arr = split("\.",$name);
		$ext = $arr[count($arr)-1];

		if($ext=="jpeg" || $ext=="jpg"){
			$img = @imagecreatefromjpeg($name);
		} elseif($ext=="png"){
			$img = @imagecreatefrompng($name);
		} elseif($ext=="gif") {
			$img = @imagecreatefromgif($name);
		}
		if(!$img)
			return false;
		$old_x = imageSX($img);
		$old_y = imageSY($img);
		if($old_x < $new_w && $old_y < $new_h) {
			$thumb_w = $old_x;
			$thumb_h = $old_y;
		} elseif ($old_x > $old_y) {
			$thumb_w = $new_w;
			$thumb_h = floor(($old_y*($new_h/$old_x)));
		} elseif ($old_x < $old_y) {
			$thumb_w = floor($old_x*($new_w/$old_y));
			$thumb_h = $new_h;
		} elseif ($old_x == $old_y) {
			$thumb_w = $new_w;
			$thumb_h = $new_h;
		}
		$thumb_w = ($thumb_w<1) ? 1 : $thumb_w;
		$thumb_h = ($thumb_h<1) ? 1 : $thumb_h;
		$new_img = ImageCreateTrueColor($thumb_w, $thumb_h);
	   
		if($transparency) {
			if($ext=="png") {
				imagealphablending($new_img, false);
				$colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
				imagefill($new_img, 0, 0, $colorTransparent);
				imagesavealpha($new_img, true);
			} elseif($ext=="gif") {
				$trnprt_indx = imagecolortransparent($img);
				if ($trnprt_indx >= 0) {
					//its transparent
					$trnprt_color = imagecolorsforindex($img, $trnprt_indx);
					$trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
					imagefill($new_img, 0, 0, $trnprt_indx);
					imagecolortransparent($new_img, $trnprt_indx);
				}
			}
		} else {
			Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
		}
	   
		imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y);
		if($border) {
			$black = imagecolorallocate($new_img, 0, 0, 0);
			imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black);
		}
		if($base64) {
			ob_start();
			imagepng($new_img);
			$img = ob_get_contents();
			ob_end_clean();
			$return = base64_encode($img);
		} else {
			if($ext=="jpeg" || $ext=="jpg"){
				imagejpeg($new_img, $newname);
				$return = true;
			} elseif($ext=="png"){
				imagepng($new_img, $newname);
				$return = true;
			} elseif($ext=="gif") {
				imagegif($new_img, $newname);
				$return = true;
			}
		}
		imagedestroy($new_img);
		imagedestroy($img);
		return $return;
	}
	
	function get_prototies($lang_id,$id_product)
	{
				$sql  = "SELECT b2bfh_prototies.*,b2bfh_product_prototies.value FROM b2bfh_prototies
				 INNER JOIN b2bfh_product_prototies ON b2bfh_product_prototies.prototies_id = b2bfh_prototies.prototies_id
				 INNER JOIN b2bfh_products ON b2bfh_product_prototies.product_id = b2bfh_products.pro_id
				 WHERE b2bfh_products.pro_id = $id_product
				 AND b2bfh_products.pro_lang_id = '$lang_id'";
				$p_prototies = $this->mod_lib->run_query($sql);
				return $p_prototies;
				
	}
}